<?php

include 'TurmaHasAlunoController.php';


define('FPDF_FONTPATH', 'font/');
require('PDF_MC_Table.php');

class AvaliacaoController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
				'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
				array('allow',  // allow all users to perform 'index' and 'view' actions
						'actions'=>array('index','view', 'imprimir','avaliacoes'),
						'users'=>array('*'),
				),
				array('allow', // allow authenticated user to perform 'create' and 'update' actions
						'actions'=>array('create','update'),
						'users'=>array('@'),
				),
				array('allow', // allow admin user to perform 'admin' and 'delete' actions
						'actions'=>array('admin','delete'),
						'users'=>array('admin'),
				),
				array('deny',  // deny all users
						'users'=>array('*'),
				),
		);
	}

	public function actions() {
		return array(
				'imprimir' => array(
						'class' => 'CViewAction',
						'defaultView' => 'frequencia',
				),
				'avaliacoes' => array(
						'class' => 'CViewAction',
						'defaultView' => 'avaliacoes',),
		);
	}

	public function actionImprimir($id) {

		$model = TurmaHasAlunoController::loadModel($id);
		$turma = Turma::model()->findByPk($model->turma_int);
		$classe = ClasseController::loadModel($turma->classe_id);
		$checked = false;
		$dados = array();
		foreach($classe->classeHasPerguntas as $classePergunta) {
			$pergunta = Pergunta::model()->findByPk($classePergunta->pergunta_id);
			$avaliacao = Avaliacao::model()->findByAttributes(array('turma_has_aluno_id'=> $model->id, 'pergunta_id'=>$pergunta->id));

			if($avaliacao == null) {
				$avaliacao = new Avaliacao;
				$avaliacao->turma_has_aluno_id = $model->id;
				$avaliacao->pergunta_id = $pergunta->id;
			}

			$dados[] = $avaliacao;
		}

		$this->printAvaliacao($dados, $model);
	}

	public function actionAvaliacoes($id) {
		$model = TurmaHasAlunoController::loadModel($id);

		$this->generateDocument($model);

	}

	private static function generateDocument($model) {

		$pdf=new PDF_MC_Table();
		$pdf->Open();
		$pdf->AddPage();
		$pdf->Image('.//css/logo_ufam.jpg',10,7,-150);
		$pdf->Image('.//css/feff.png',182,5,-212);
		$pdf->SetFont('Arial','B',12);
		$pdf->Cell(0,5,'UNIVERSIDADE FEDERAL DO AMAZONAS ',0,1, 'C');
		$pdf->Cell(0,5,utf8_decode('FACULDADE DE EDUCAÇÃO FÍSICA E FISIOTERAPIA'),0,1, 'C');
		$pdf->Cell(0,5,utf8_decode('PROGRAMA DE ATIVIDADES MOTORAS PARA DEFICIENTES - PROAMDE'),0,1,'C');
		$pdf->Ln(10);
		$pdf->SetFont('Arial','B',16);
		$pdf->Image('.//css/proamde.png',88,null,-260);

		$pdf->Ln(6);
		$pdf->Cell(0,5,utf8_decode('Avaliações Diárias'),0,1,'C');
		$pdf->SetFont('Arial','B',14);
		$pdf->Ln(10);
		$pdf->Cell(0,8, utf8_decode("Aluno: " .$model->aluno->pessoa->nome),0,1);
		$pdf->Cell(0,8, utf8_decode('Turma: ' . $model->turmaInt->nome) ,0,1);

		$pdf->Ln(8);
		
		if($model->avaliacaos != null && !empty($model->avaliacaos)) {
		
		$pdf->SetWidths(array(35, 85, 65,));

		$pdf->SetFillColor(192,217,217);
		$pdf->SetTextColor(0);
		$pdf->SetDrawColor(0,0,0);
		$pdf->SetLineWidth(.2);
		$pdf->SetFont('','B', 10);

		$pdf->Row(array(utf8_decode('Aula'), utf8_decode('Avaliação'), utf8_decode('Responsável')));

		$pdf->SetFillColor(224,235,255);
		$pdf->SetTextColor(0);
		$pdf->SetFont('');
		$pdf->SetFont('Arial','',9);
		
		
			foreach($model->avaliacaos as $avaliacao) {
				$responsavel = "";
				$resp = Funcionario::model()->findByAttributes(array('id'=>$avaliacao->responsavel_id));
				if($resp != null) {
					$responsavel = $resp->pessoa->nome;
				}
				$pdf->Row(array(utf8_decode("(".$avaliacao->aula->numero.") - ".$avaliacao->aula->data), utf8_decode($avaliacao->texto), utf8_decode($responsavel)));
			}
		} else {
			$pdf->Ln(10);
			$pdf->Cell(0,5,utf8_decode('Aluno não possui avaliações diárias cadastradas na Turma.'),0,1,'C');
		}
		
		$pdf->Output('avaliacao_diaria.pdf');
			
		$path = Yii::app()->request->hostInfo . Yii::app()->request->baseURL . '/avaliacao_diaria.pdf';
		
		return Yii::app()->getRequest()->sendFile('avaliacao_diaria_'.$model->id.'.pdf', @file_get_contents($path));
		

	}

	private function printAvaliacao($dados, $model) {

		$pdf=new PDF_MC_Table();
		$pdf->Open();
		$pdf->AddPage();

		$pdf->Image('.//css/logo_ufam.jpg',10,7,-150);
		$pdf->Image('.//css/feff.png',182,5,-212);
		$pdf->SetFont('Arial','B',12);
		$pdf->Cell(0,5,'UNIVERSIDADE FEDERAL DO AMAZONAS ',0,1, 'C');
		$pdf->Cell(0,5,utf8_decode('FACULDADE DE EDUCAÇÃO FÍSICA E FISIOTERAPIA'),0,1, 'C');
		$pdf->Ln(10);
			
		$pdf->SetFont('Arial','B',12);
		$pdf->Image('.//css/proamde.png',88,null,-260);
		$pdf->Ln(8);
		$pdf->Cell(0,5,utf8_decode('AVALIAÇÃO DO ALUNO'),0,1, 'C');
		$pdf->Ln(5);
		$pdf->Cell(0,5,utf8_decode('Turma: '.$model->turmaInt->nome),0,1, 'L');
		$pdf->Cell(0,5,utf8_decode('Aluno: '.$model->aluno->pessoa->nome),0,1, 'L');

		$pdf->Ln(6);
		$pdf->SetWidths(array(35, 75, 40, 40));
		$areas = array();
		$position = 0;
		foreach($dados as $dado) {
			$position ++;
			$pergunta = Pergunta::model()->findByPk($dado->pergunta_id);
			if(!in_array($pergunta->area, $areas)) {
				$areas[] = $pergunta->area;
				$pdf->Ln(4);
				$pdf->SetFillColor(192,217,217);
				$pdf->SetTextColor(0);
				$pdf->SetDrawColor(0,0,0);
				$pdf->SetLineWidth(0);
				$pdf->SetFont('','B', 10);

				$pdf->Row(array(utf8_decode('Nº'), utf8_decode(Utils::traduzirArea($pergunta->area)), utf8_decode('1ª Avaliação'), utf8_decode('2ª Avaliação')));
			}

			$pdf->SetFillColor(224,235,255);
			$pdf->SetTextColor(0);
			$pdf->SetFont('');
			$pdf->SetFont('Arial','',8);

			$pdf->Row(array(utf8_decode($position), utf8_decode($pergunta->pergunta), utf8_decode(Pergunta::$answers[$dado->resposta1]), utf8_decode(Pergunta::$answers[$dado->resposta2])));
		}

		$dia = date('d');
		$mes = date('F');
		$ano = date('Y');
			
		$mes_num = "";// Dia da semana.
			
		if($mes == "January"){
			$mes_num = "Janeiro";
		}elseif($mes == "February"){
			$mes_num = "Fevereiro";
		}elseif($mes == "March"){
			$mes_num = "Março";
		}elseif($mes == "April"){
			$mes_num = "Abril";
		}elseif($mes == "May"){
			$mes_num = "Maio";
		}elseif($mes == "June"){
			$mes_num = "Junho";
		} elseif($mes == "July") {
			$mes_num = "Julho";
		} elseif($mes == "August"){
			$mes_num = "Agosto";
		} elseif ($mes == "September") {
			$mes_num = "Setembro";
		} elseif ($mes == "October") {
			$mes_num = "Outubro";
		} elseif($mes == "November") {
			$mes_num = "Novembro";
		}else{
			$mes_num = "Dezembro";
		}

		$pdf->Ln(12);
		$pdf->SetFont('Arial','B',12);

		$pdf->Cell(0,5,utf8_decode('Manaus, '.$dia.' de '.$mes_num.' de '. $ano),0,1, 'C');
			
		$pdf->Ln(15);
		$pdf->Cell(0,5,'_______________________________________',0,1, 'C');
		$pdf->SetFont('Arial','B',12);
		$pdf->Cell(0,5,utf8_decode('Assinatura do Responsável'),0,1, 'C');

		$pdf->Output('avaliacao.pdf');
			
		$path = Yii::app()->request->hostInfo . Yii::app()->request->baseURL . '/avaliacao.pdf';

		return Yii::app()->getRequest()->sendFile('avaliacao'.$model->id.'.pdf', @file_get_contents($path));

	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
				'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Avaliacao;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Avaliacao']))
		{
			$model->attributes=$_POST['Avaliacao'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
				'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Avaliacao']))
		{
			$model->attributes=$_POST['Avaliacao'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
				'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex($id)
	{
		$model = TurmaHasAlunoController::loadModel($id);
		$turma = Turma::model()->findByPk($model->turma_int);
		$classe = ClasseController::loadModel($turma->classe_id);
		$checked = false;

		foreach($classe->classeHasPerguntas as $classePergunta) {
			$pergunta = Pergunta::model()->findByPk($classePergunta->pergunta_id);
			$avaliacao = Avaliacao::model()->findByAttributes(array('turma_has_aluno_id'=> $model->id, 'pergunta_id'=>$pergunta->id));

			if($avaliacao == null) {
				$avaliacao = new Avaliacao;
				$avaliacao->turma_has_aluno_id = $model->id;
				$avaliacao->pergunta_id = $pergunta->id;
			}

			if(isset($_POST['resposta1_'.$pergunta->id])) {
				$avaliacao->resposta1 =  $_POST['resposta1_'.$pergunta->id];
				$avaliacao->resposta2 = $_POST['resposta2_'.$pergunta->id];
				$avaliacao->save();
				$checked = true;
			}
		}

		if($checked) {
			$this->redirect(array('turmaHasAluno/view','id'=>$model->id));
		}

		$this->render('index',array(
				'model'=>$model,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Avaliacao('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Avaliacao']))
			$model->attributes=$_GET['Avaliacao'];

		$this->render('admin',array(
				'model'=>$model,
		));
	}

	public function generateAvaliacoes($form, $model) {
		$turma = Turma::model()->findByPk($model->turma_int);
		$classe = ClasseController::loadModel($turma->classe_id);
		$position = 0;
		$areas = array();
		echo '<Table>';
		echo '<tr><td></td><td></td><td></td><td></td><tr/>';
		foreach($classe->classeHasPerguntas as $classePergunta) {
			$position ++;
			$pergunta = Pergunta::model()->findByPk($classePergunta->pergunta_id);
			$avaliacao = Avaliacao::model()->findByAttributes(array('turma_has_aluno_id'=> $model->id, 'pergunta_id'=>$pergunta->id));
			if($avaliacao == null) {
				$avaliacao =new Avaliacao;
			}
			if(!in_array($pergunta->area, $areas)) {
				echo '<tr>';
				echo '<td><b>Nº:</b></td>';
				echo '<td><b>' .Utils::traduzirArea($pergunta->area)."</b></td>";
				echo '<td><b align="center">1ª Avaliação</b></td>';
				echo '<td><b align="center">2ª Avaliação</b></td>';
				echo '</tr>';
				$areas[] = $pergunta->area;
			}
			echo '<tr>';
			echo '<td>' .$position."</td>";
			echo '<td>' .$pergunta->pergunta."</td>";
			if($pergunta->area == "AVALIACAO FISICA") {
				echo '<td>' .$form->textField($avaliacao, 'resposta1', array('name'=>'resposta1_'.$pergunta->id, 'class'=>'span2', 'value'=>$avaliacao->resposta1)).'</td>';
				echo '<td>' .$form->textField($avaliacao, 'resposta2', array('name'=>'resposta2_'.$pergunta->id, 'class'=>'span2', 'value'=>$avaliacao->resposta2)).'</td>';
			} else {
				echo '<td>'.$form->dropDownList($avaliacao, 'resposta1', Pergunta::$answers, array('name'=>'resposta1_'.$pergunta->id,'class'=>'span2', 'value'=>$avaliacao->resposta1,'empty' => '')).'</td>';
				echo '<td>'.$form->dropDownList($avaliacao, 'resposta2', Pergunta::$answers, array('name'=>'resposta2_'.$pergunta->id, 'class'=>'span2', 'value'=>$avaliacao->resposta2 ,'empty' => '')).'</td>';
			}
			echo '</tr>';
		}
		echo '</Table>';
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Avaliacao::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='avaliacao-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
